import {Component, ViewChild} from '@angular/core';
import {Events, IonicPage, NavController, NavParams, Slides, ToastController} from 'ionic-angular';
import {IndexProvider} from "../../providers/index/index.provider";
import {ThemeBrowserService} from "../../services/native/theme-browser/theme-browser.service";
import {FileService} from "../../services/native/file/file.service";
import * as _ from 'lodash';
import * as moment from 'moment';
import {MessageBushService} from "../../services/common/message-bush.service";
import {JPushControlerService} from "../../services/native/push/jpush-controler.service";
import {CacheImgService} from "../../services/native/cache-img/cache-img.service";

@IonicPage()
@Component({
    selector: 'page-index',
    templateUrl: 'index.html',
    providers: [
        IndexProvider,
        FileService,
        ThemeBrowserService
    ]
})
export class IndexPage {
    @ViewChild('indexBanner') bannerSlides: Slides;
    @ViewChild('topMsgSlide') topMsgSlides: Slides;
    @ViewChild('hotSlides') hotSlides: Slides;

    //banner 数据
    bannerList: Array<any> = [];
    //头条 数据
    topMsgList: Array<any> = [];
    //资讯 数据
    hotList: Array<any> = [];

    setHock: any;
    //未读消息数量
    unReadMsg: number = 0;

    //日程列表
    sheduleList: any = [];

    moment = moment;

    //当天日期
    todayDate: Date = new Date();

    //角色和职级
    roles: string;
    agentLevel: string;

    bannerImgDefaultUrl = './assets/images/index/banner_default.jpg';
    newImgDefaultUrl = './assets/images/index/news_default.jpg';

    sequence: number = 0;

    constructor(public navCtrl: NavController,
                public navParams: NavParams,
                public fileService: FileService,
                public toastCtrl: ToastController,
                private themeBrowserService: ThemeBrowserService,
                private jPushControlerService: JPushControlerService,
                private events: Events,
                private indexProvider: IndexProvider,
                private cacheImg: CacheImgService) {
    }

    ionViewDidLoad() {
        this.bannerList = [];
        this.hotList = [];
        this.topMsgList = [];
        this.roles = this.computeRoles();
        this.agentLevel = localStorage.getItem('agentLevel');
    }

    ionViewWillEnter() {
        this.jPushControlerService.init();
        this.jPushControlerService.resumePush();
        this.jPushControlerService.intervalSetAlias();
    }

    // 处理多角色
    private computeRoles() {
        let fullRoles = localStorage.getItem('fullRoles');
        if (fullRoles.indexOf('1') > -1) {
            return '1';
        } else {
            return fullRoles.split(',')[0];
        }
    }

    ionViewDidEnter() {
        this.getAllInfo();
        this.setSlidesAutoPlay();
        this.getRecentShedule();
        this.getUnReadMsg();

        this.setAutoPlay();

        let status = MessageBushService.getMessage(MessageBushService.keys.indexSheduleSaveSuccess);
        if (status === '1') {
            this.getRecentShedule();
            MessageBushService.setMessage(MessageBushService.keys.indexSheduleSaveSuccess, '0');
        }
    }

    ionViewDidLeave() {
        this.leaveHandler();
    }

    leaveHandler = () => {
        this.stopAutoPlay();
        clearInterval(this.setHock);
    };
    pushIDTimer: number = 0;

    showPushID() {
        if (this.pushIDTimer <= 5) {
            this.pushIDTimer++
        } else {
            this.pushIDTimer = 0;
            alert(localStorage.getItem('RegistrationID'));
            alert(localStorage.getItem('SetAlias'));
        }

        //this.navCtrl.push('InformationLinkPage')
    }

    setAutoPlay() {
        let self = this;
        setTimeout(() => {
            if (self.bannerList.length > 0 && self.bannerSlides) {
                self.bannerSlides.autoplay = 2000;
            }

            if (self.topMsgList.length > 0 && self.topMsgSlides) {
                self.topMsgSlides.autoplay = 2000;

            }
            if (self.hotList.length > 0 && self.hotSlides) {
                self.hotSlides.autoplay = 2000;
            }
        }, 2000);
    }

    setSlidesAutoPlay() {
        this.setHock = setInterval(() => {
            if (this.bannerList.length > 0 && this.bannerSlides) {
                this.bannerSlides.autoplay = 2000;
                setTimeout(() => {
                    if (!this.bannerSlides._activeIndex) {
                        this.bannerSlides._activeIndex = 0;
                    }
                    try {
                        this.bannerSlides.startAutoplay();
                    } catch (err) {

                    }
                }, 0);
            }

            if (this.topMsgList.length > 0 && this.topMsgSlides) {
                this.topMsgSlides.autoplay = 2000;
                setTimeout(() => {
                    if (!this.topMsgSlides._activeIndex) {
                        this.topMsgSlides._activeIndex = 0;
                    }
                    try {
                        this.topMsgSlides.startAutoplay();
                    } catch (err) {

                    }
                }, 0);
            }
            if (this.hotList.length > 0 && this.hotSlides) {
                this.hotSlides.autoplay = 2000;
                setTimeout(() => {
                    if (!this.hotSlides._activeIndex) {
                        this.hotSlides._activeIndex = 0;
                    }
                    try {
                        this.hotSlides.startAutoplay();
                    } catch (err) {

                    }
                }, 0);
            }
        }, 3000);
    }

    getAllInfo() {
        this.getBannerList();
        this.getTopAndInformationList();
    }

    /*停止幻灯片滚动*/
    stopAutoPlay() {
        if (this.bannerList.length > 0) {
            this.bannerList = [];
            this.bannerSlides.stopAutoplay();
        }

        if (this.topMsgList.length > 0) {
            this.topMsgList = [];
            this.topMsgSlides.stopAutoplay();
        }

        if (this.hotList.length > 0) {
            this.hotList = [];
            this.hotSlides.stopAutoplay();
        }
    }

    doRefresh(refresher) {
        this.getAllInfo();
        this.getRecentShedule();
        this.getUnReadMsg();
        setTimeout(() => {
            this.setAutoPlay();
            refresher.complete();
        }, 1000);
    }

    getBannerList() {
        this.bannerList = [];
        this.indexProvider.getBannerList().subscribe((homeData) => {
            this.indexProvider.getBannerPreview().subscribe((prevData) => {
                if (prevData.length > 0) {
                    prevData.forEach((el) => {
                        el.isPrev = true;
                    });
                }
                let tempBannerList = prevData.concat(homeData);
                if (tempBannerList.length > 0) {
                    this.fileService.getAzureInfo().subscribe((data) => {
                        tempBannerList.forEach((ele) => {
                            let imgUrl = _.cloneDeep(ele.imgUrl);
                            ele.imgUrl = this.bannerImgDefaultUrl;
                            if (imgUrl) {
                                // ele.realImgUrl = this.fileService.getCompletePath(imgUrl, data.azureInfo);
                                this.cacheImg.getImgPath(imgUrl, data.azureInfo).then((res) => {
                                    ele.realImgUrl = res;
                                    this.imagesLoad(ele);
                                }).catch(() => {
                                    ele.realImgUrl = this.fileService.getCompletePath(imgUrl, data.azureInfo);
                                    this.imagesLoad(ele);
                                });
                            }
                        });
                        this.bannerList = tempBannerList;
                    }, err => {
                        console.log(err);
                    });
                }
            });
        });
    }

    /**
     * banner图片与热点资讯图片，如果未完全加载出来，先使用默认图片显示
     * 加载完成后，再用真正的图片替换
     * @param item
     */
    imagesLoad(item) {
        let url = item.realImgUrl;
        let img = new Image();
        img.onload = function () {
            if (img.complete == true) {
                item.imgUrl = url;
            }
        };

        img.src = url;
    }

    /**获取头条与资讯数据*/
    getTopAndInformationList() {
        this.hotList = [];
        this.indexProvider.getTopAndInformationList().subscribe((res) => {
            this.indexProvider.getPreviewHotList().subscribe((previewHotData) => {
                if (previewHotData.length > 0) {
                    previewHotData.forEach((el) => {
                        el.isPrev = true;
                    });
                }
                let normalHotData = res.hot; //热点资讯
                let hotList = previewHotData.concat(normalHotData);
                if (hotList.length > 0) {
                    this.fileService.getAzureInfo().subscribe((data) => {
                        hotList.forEach((ele) => {
                            let imgUrl = _.cloneDeep(ele.imgUrl);
                            ele.imgUrl = this.newImgDefaultUrl;
                            if (imgUrl) {
                                this.cacheImg.getImgPath(imgUrl, data.azureInfo)
                                    .then((res) => {
                                        ele.realImgUrl = res;
                                        this.imagesLoad(ele);
                                    })
                                    .catch((err) => {
                                        ele.realImgUrl = this.fileService.getCompletePath(imgUrl, data.azureInfo);
                                        this.imagesLoad(ele);
                                    });
                            }
                        });
                        this.hotList = hotList;
                    }, err => {
                        console.log(err);
                    });
                }
            });
            this.indexProvider.getPreviewMsgList().subscribe((prevTopData) => {
                if (prevTopData.length > 0) {
                    prevTopData.forEach((el) => {
                        el.isPrev = true;
                    });
                }
                let topMsgList = prevTopData.concat(res.newest),//头条信息
                    tempTopMsgList = topMsgList.length > 2 ? topMsgList.splice(0, 2) : topMsgList;
                tempTopMsgList.forEach((msg) => {
                    let title = msg.title;
                    if (title.length > 16) {
                        msg.title = title.substr(0, 13) + '...';
                    }
                })

                this.topMsgList = tempTopMsgList;

            });
        });
    }

    /**跳转Banner详情页页*/
    toBannerDetail(item) {
        if (item.linkUrl) {
            this.goToBrowerPlatform(item.title, item.id, item.linkUrl, item.status);
            return false;
        }
        this.navCtrl.push('BannerPage', {
            id: item.id
        });
    }

    /**跳转资讯列表*/
    toHeaderList() {
        this.navCtrl.push('InformationListPage');
    }

    /**头条信息详细页跳转*/
    toDetailHeaderMsg(item) {
        if (item.linkUrl) {
            this.goToBrowerPlatform(item.title, item.id, item.linkUrl, item.status);
            return false;
        }

        this.navCtrl.push('InformationDetailPage', {
            id: item.id,
            url: item.linkUrl,
            status: item.isPrev ? true : false
        });
    }

    /**客户 日程 消息 更多 跳转事件*/
    goMainPage(pageClassName: string) {
        this.navCtrl.push(pageClassName);
    }

    /**
     * 打开外链
     * @param {string} url  外链URL，带上参数
     */
    // 外链到浏览器平台
    goToBrowerPlatform(name, id, url, status) {
        this.themeBrowserService.openBrowser(url, {
            name: name,
            id: id,
            status: status,
            callback1: (id) => null,
            callback2: (id) => null
        });
    }

    /**
     * 获取未读消息数
     */
    getUnReadMsg() {
        this.indexProvider.getUnReadMsg().subscribe(res => {
            this.unReadMsg = Number(res);
        });
    }

    /**
     * 获取最近日程
     */
    getRecentShedule() {
        this.indexProvider.getRecentShedule().subscribe(res => {
            // this.sheduleList = res;
            let result: Array<any> = res as Array<any>;
            for (var i = 0; i < result.length; i++) {
                result[i]['tags'] = this.formatSheduleDate(result[i]['startTime'], result[i]['endTime']);
                result[i]['status'] = moment(this.todayDate.getTime()).unix() > result[i]['startTime'] ? 'Y' : 'N';
            }
            this.sheduleList = result;
        });
    }

    /**
     * 跳转日程详情
     * @param {number} id
     * @param item
     */
    goSheduleDetail(id: number, item: any) {
        let data = JSON.parse(JSON.stringify(item));
        // let currentTime = moment(this.todayDate.getTime()).format('YYYY/MM/DD') + ' 00:00:00';
        // let currentTimestap = moment(new Date(currentTime).getTime()).unix();
        let currentTime = moment(data['startTime'] * 1000).format('YYYY/MM/DD') + ' 00:00:00';
        let currentTimestap = moment(new Date(currentTime).getTime()).unix();
        this.navCtrl.push('ScheduleAddPage', {id: id, date: currentTimestap, item: data, fromPage: 'index'})
    }

    /**
     * 跳转添加日程
     */
    goToAddSchedule() {
        let currentTime = moment(this.todayDate.getTime()).format('YYYY/MM/DD') + ' 00:00:00';
        let currentTimestap = moment(new Date(currentTime).getTime()).unix();
        this.navCtrl.push('ScheduleAddPage', {date: currentTimestap, fromPage: 'index'})
    }

    /**
     * 格式化日程时间
     * @param {number} startTime
     * @param {number} endTime
     */
    private formatSheduleDate(startTime: number, endTime: number) {
        let dateArr = [];

        let startDate = moment(startTime * 1000).format('YYYY/MM/DD');
        let endDate = moment(endTime * 1000).format('YYYY/MM/DD');
        let nowDate = moment(this.todayDate.getTime()).format('YYYY/MM/DD');
        let nextDate = moment(this.todayDate.getTime()).add(1, 'days').format('YYYY/MM/DD');

        //检查是否当天，如果是，显示今天 x:xx - y:yy
        if (startDate == endDate && endDate == nowDate) {
            // dateArr.push('今天 '+ moment(startTime*1000).format('YYYY/MM/DD HH:mm').split(' ')[1]+
            // ' - '+moment(endTime*1000).format('YYYY/MM/DD HH:mm').split(' ')[1]);
            // return dateArr;
            dateArr.push(moment(startTime * 1000).format('YYYY/MM/DD HH:mm') +
                ' - ' + moment(endTime * 1000).format('YYYY/MM/DD HH:mm').split(' ')[1]);
            return dateArr;
        }

        //检查是否明天，如果是，显示明天 x:xx - y:yy
        if (startDate == nextDate && nextDate == endDate) {
            // dateArr.push('明天 '+ moment(startTime*1000).format('YYYY/MM/DD HH:mm').split(' ')[1]+
            //     ' - '+moment(endTime*1000).format('YYYY/MM/DD HH:mm').split(' ')[1])
            // return dateArr;
            dateArr.push(moment(startTime * 1000).format('YYYY/MM/DD HH:mm') +
                ' - ' + moment(endTime * 1000).format('YYYY/MM/DD HH:mm').split(' ')[1])
            return dateArr;
        }

        //不是今天或明天，但是同一天
        if (startDate == endDate && startDate != nowDate && startDate != nextDate) {
            dateArr.push(moment(startTime * 1000).format('YYYY/MM/DD HH:mm') +
                ' - ' + moment(endTime * 1000).format('YYYY/MM/DD HH:mm').split(' ')[1])
            return dateArr;
        }

        //如果是跨天，显示两行 xxxx/xx/xx xx:xx (开始)  xxxx/xx/xx xx:xx (结束)
        if (startDate != endDate) {
            dateArr.push(moment(startTime * 1000).format('YYYY/MM/DD HH:mm') + '（开始）');
            dateArr.push(moment(endTime * 1000).format('YYYY/MM/DD HH:mm') + '（结束）');
        }

        return dateArr;
    }
}
